package com.cicadasmall.system.service.impl;

import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.common.resp.R;
import com.cicadasmall.mybatis.annotation.DataScope;
import com.cicadasmall.redis.annotation.RedisCache;
import com.cicadasmall.system.dto.AreaInputDTO;
import com.cicadasmall.system.dto.AreaQueryDTO;
import com.cicadasmall.system.dto.AreaUpdateDTO;
import com.cicadasmall.data.domain.AreaDO;
import com.cicadasmall.system.service.IAreaService;
import com.cicadasmall.system.vo.AreaVO;
import com.cicadasmall.data.mapper.SysAreaMapper;
import com.cicadasmall.system.wrapper.AreaWrapper;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 区域 服务实现类
 * </p>
 *
 * @author jin
 * @since 2020-09-06
 */
@Service
public class AreaServiceImpl extends BaseService<SysAreaMapper, AreaDO> implements IAreaService {

    @RedisCache(key = "area_cache", fieldKey = "tree")
    @Override
    public List<AreaVO> getTree() {
        return AreaWrapper.newBuilder().treeVO(baseMapper
                .selectList(getLambdaQueryWrapper().orderByAsc(AreaDO::getId)));
    }

    @DataScope
    @Override
    public R list(AreaQueryDTO areaQueryDTO) {
        List<AreaDO> areaList = baseMapper.selectList(getLambdaQueryWrapper(areaQueryDTO.convertToEntity()));
        return R.ok(AreaWrapper.newBuilder().listVO(areaList));
    }

    @Override
    public R save(AreaInputDTO areaInputDTO) {
        AreaDO area = areaInputDTO.convertToEntity();
        baseMapper.insert(area);
        return R.ok(true);
    }

    @Override
    public R update(AreaUpdateDTO areaUpdateDTO) {
        AreaDO area = areaUpdateDTO.convertToEntity();
        baseMapper.updateById(area);
        return R.ok(true);
    }

    @Override
    public R findById(Serializable id) {
        AreaDO area = baseMapper.selectById(id);
        return R.ok(AreaWrapper.newBuilder().entityVO(area));
    }

    @Override
    public R deleteById(Serializable id) {
        baseMapper.deleteById(id);
        return R.ok(true);
    }

}
